package com.szt.sy.controller.base;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.szt.sy.entity.SessionUser;
import com.szt.sy.entity.system.User;
import com.szt.sy.exception.ApplicationRuntimeException;
import com.szt.sy.util.date.DateUtil;
import com.szt.sy.util.security.SecurityUtils;
import com.szt.sy.util.web.AjaxUtils;
import com.szt.sy.vo.rep.base.RepBaseVO;
import com.szt.sy.vo.rep.base.ResultCode;

/***
 * 后台管理控制器基类
 * 
 * @author wwy
 *
 */
public class AdminBaseController extends BaseController {
	
	@ExceptionHandler(value = Exception.class)
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		logger.error("应用异常" + DateUtil.getTime(), ex);
		ModelAndView mv = new ModelAndView();
		if (AjaxUtils.isAjaxRequest(request) || AjaxUtils.isAjaxUploadRequest(request)) {
			response.setContentType("application/json;charset=UTF-8");
			RepBaseVO<String> repVO = new RepBaseVO<>();
			if (ex instanceof ApplicationRuntimeException) {
				repVO.setCode(ResultCode.COMMON_FAIL).setMes(ex.getMessage());
			} else {
				repVO.setCode(ResultCode.COMMON_FAIL).setMes("程序错误");
			}
			try {
				response.getWriter().print(JSON.toJSONString(repVO));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			mv.setViewName("error");
			mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
		}
		return mv;
	}
	
	/** 获取后台登录用户信息 */
	public SessionUser getLoginSessionUser() {
		SessionUser sessionUser = SecurityUtils.getSessionUser();
		if (sessionUser == null) {
			return null;
		}
		if (sessionUser.getUser() == null) {
			return null;
		}
		return sessionUser;
	}
	
	/***
	 * 获取后台登录用户
	 * 
	 * @return
	 */
	public User getLoginUser() {
		SessionUser sessionUser = getLoginSessionUser();
		if (sessionUser == null) {
			return null;
		}
		return sessionUser.getUser();
	}
	
	/** 获取后台登录用户Id */
	public String getLoginUserId() {
		SessionUser sessionUser = getLoginSessionUser();
		if (sessionUser == null) {
			return null;
		}
		if (StringUtils.isBlank(sessionUser.getUser().getId())) {
			return null;
		}
		return sessionUser.getUser().getId();
	}
}
